import json
import os
import logging
import chardet  # 新增编码检测库

# 创建日志记录器
def create_logger():
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(levelname)s - %(message)s | 文件:%(filename)s,函数:%(funcName)s'
    )
    return logging

# 加载语言数据（带编码自动检测）
def load_language_data():
    logging.info("开始加载语言数据...")
    default_data = {  # 文件不存在时的默认数据
        "current_language": "zh",
        "zh": {
            "app_title": "图像处理器",
            "open_original": "打开原图",
            "open_grayscale": "打开原图转灰度图",
            "merge_channels": "合并打开多个子图",
            "save_image": "保存当前主显示区内容",
            "language": "语言",
            "confirm_restart": "确认重启",
            "restart_warning": "重启应用程序将导致当前状态和数据丢失,确定要重启吗?",
            "exit": "退出",
            "file": "文件",
            "details": "细节",
            "info": "主显示区信息",
            "info_str": "图像文件名: {0}\n总像素数: {1:,}\n图像形状: {2}\n图像通道数: {3}\n像素数据类型: {4}",
            "crop": "裁剪",
            "reset": "重置原图",
            "edit": "编辑",
            "split": "分割",
            "split_channels": "分割所有子通道",
            "error": "错误"
        },
        "en": {
            "app_title": "Image Processor",
            "open_original": "Open Original",
            "open_grayscale": "Open Grayscale",
            "merge_channels": "Merge Channels",
            "save_image": "Save Current",
            "language": "Language",
            "confirm_restart": "Confirm Restart",
            "restart_warning": "Restarting the application will cause current state and data to be lost. Are you sure you want to restart?",
            "exit": "Exit",
            "file": "File",
            "details": "Details",
            "info": "Image Info",
            "info_str": "Image Path: {0}\nPixel Count: {1:,}\nImage Shape: {2}\nChannels: {3}\ndtype: {4}",
            "crop": "Crop",
            "reset": "Reset",
            "edit": "Edit",
            "split": "Split",
            "split_channels": "Split Channels",
            "error": "Error"
        }
    }
    
    if not os.path.exists('language.json'):
        logging.warning("language.json不存在，创建默认文件")
        write_language_data(default_data, None, None)  # 初始化文件
        return default_data
    
    try:
        # 检测文件编码
        with open('language.json', 'rb') as f:
            raw_data = f.read(1024)
            encoding = chardet.detect(raw_data)['encoding'] or 'utf-8'
            logging.info(f"检测到文件编码：{encoding}")
        
        # 用检测到的编码读取
        with open('language.json', 'r', encoding=encoding, errors='replace') as f:
            try:
                language_data = json.load(f)
                logging.info("语言数据加载成功")
                return language_data
            except json.JSONDecodeError as e:
                logging.error(f"JSON解析失败：{e}，尝试恢复默认数据")
                return default_data
    except Exception as e:
        logging.error(f"加载语言数据失败：{e}，使用默认数据")
        return default_data

# 写入语言数据（强制UTF-8）
def write_language_data(language_data, key=None, value=None):
    if key and value:  # 单个键值对更新
        language_data[key] = value
    
    try:
        with open('language.json', 'w', encoding='utf-8') as f:
            json.dump(language_data, f, ensure_ascii=False, indent=4)
        logging.info("语言数据已保存（UTF-8编码）")
    except Exception as e:
        logging.error(f"保存失败：{e}")
        raise

#################### 以下是载入代码 ####################
logging = create_logger()
language_data = load_language_data()

# 初始化时检查并修复编码（首次运行自动转换）
if not os.path.exists('language.json'):
    write_language_data(language_data)
else:
    with open('language.json', 'rb') as f:
        if chardet.detect(f.read())['encoding'].lower() != 'utf-8':
            logging.warning("检测到非UTF-8编码，正在转换...")
            write_language_data(language_data)